package com.plugin.sharding;

import java.util.Collection;
import java.util.LinkedHashSet;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;

@Slf4j
@Data
public class TableShardingByInteger implements CommonTableShardingAlgorithm<Integer> {
	private String logicTableName;
	
	public TableShardingByInteger(String logicTableName) {
		this.logicTableName = logicTableName;
	}

	/**
	 * 查询条件是=的时候
	 */
	public String doEqualSharding(Collection<String> tableNames,
			ShardingValue<Integer> shardingValue) {
		Integer valueTemp = shardingValue.getValue();
		String fixedTableName = Utils.genTableName(logicTableName, Long.valueOf(valueTemp));
		if(tableNames.contains(fixedTableName)) {
			log.info("tableName is : {}", fixedTableName);
			return fixedTableName; 
		}
		log.info("没有合适找到对应的表名： modStr : {}", Utils.getShardingIndex(shardingValue.getValue()));
		throw new IllegalArgumentException("没有合适找到对应的表名： " + Utils.getShardingIndex(shardingValue.getValue()));
	}

	/**
	 * 查询条件是in的时候
	 */
	public Collection<String> doInSharding(Collection<String> tableNames,
			ShardingValue<Integer> shardingValue) {
		Collection<String> result = new LinkedHashSet<String>(tableNames.size());
//		for (Integer queryValue : shardingValue.getValues()) {
//			String fixedTableName = Utils.genTableName(logicTableName, queryValue);
//			if(tableNames.contains(fixedTableName)) {
//				log.info("tableName is : {}", fixedTableName);
//				result.add(fixedTableName);
//			} else {
//				log.info("没有合适找到对应的表名： modStr : {}", Utils.getShardingIndex(queryValue));
//			}
//		}
		return result;
	}

	/**
	 * TODO 暂未实现
	 * 查询条件是between的时候
	 */
	public Collection<String> doBetweenSharding(Collection<String> tableNames,
			ShardingValue<Integer> shardingValue) {
		Collection<String> result = new LinkedHashSet<String>(tableNames.size());
//		Range<Long> range = (Range<Long>) shardingValue.getValueRange();
//		for (long i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
//			Long modValue = shardingValue.getValue();
//			String modStr = modValue.toString();
//			for (String each : tableNames) {
//				if (each.endsWith(modStr)) {
//					result.add(each);
//				}
//			}
//		}
		return result;
	}

}
